package com.steamedfish.auctionsecurityserveroauth2.config.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonParser;
import com.steamedfish.auctionsecurityserveroauth2.entiry.*;
import com.steamedfish.auctionsecurityserveroauth2.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Service(value = "myUserDetailsService")
public class UserDetailService implements UserDetailsService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserMapper userMapper;

    @DS("steamed_fish_auction_security")
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //判断登陆名是否为空
        if (s == null) {
            throw new RuntimeException("登陆名不能为空");
        }
        //取出用户信息
        UserEntiry user = null;
        if (s.contains("@")) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("mail", s);
            user = userMapper.selectOne(queryWrapper);
        } else if (s.length() == 11) {
            try {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("telephone", s);
                user = userMapper.selectOne(queryWrapper);
            } catch (Exception e) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("username", s);
                user = userMapper.selectOne(queryWrapper);
            }
        } else {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", s);
            user = userMapper.selectOne(queryWrapper);
        }

        Collection<GrantedAuthority> authList = getAuthorities(user);

        UserEntiry userjson = new UserEntiry();
        BeanUtils.copyProperties(user, userjson);
        userjson.setPassword("");

        String json = JSON.toJSONString(userjson);

        //封装好用户信息
        UserDetails userDetails = new User(json
                , user.getPassword()
                , true
                , true
                , true
                , true
                , authList);
        //返回用户信息

        return userDetails;
    }


    private Collection<GrantedAuthority> getAuthorities(UserEntiry userEntiry) {
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        //选出角色放入
        QueryWrapper roleWrapper = new QueryWrapper();
        roleWrapper.eq("user_id", userEntiry.getId());
        UserRoleEntiry userRoleEntiry = userRoleMapper.selectOne(roleWrapper);

        QueryWrapper b = new QueryWrapper();
        b.eq("id", userRoleEntiry.getRoleId());
        RoleEntiry roleEntiry = roleMapper.selectOne(b);
        packet(authList, roleEntiry.getRoleName());
        //选出权限放入
        QueryWrapper c = new QueryWrapper();
        c.eq("role_id", roleEntiry.getId());
        RolePermissionEntiry rolePermissionEntiry = rolePermissionMapper.selectOne(c);
        QueryWrapper d = new QueryWrapper();
        d.eq("id", rolePermissionEntiry.getPermissionId());
        PermissionEntiry permissionEntiry = permissionMapper.selectOne(d);
        packet(authList, permissionEntiry.getCode());
        return authList;
    }

    private void packet(List<GrantedAuthority> authList, String auth) {
        String[] list = auth.split(",");
        for (int i = 0; i < list.length; i++) {
            authList.add(new SimpleGrantedAuthority(list[i]));
        }
    }
}